import os
import random
import json

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, FileResponse
from django.conf import settings
from openai import OpenAI
from rest_framework.response import Response
from rest_framework.views import APIView

from job.models import ResumeParseData
from user.models import User, JobInfo, WorkExperience
from utils.qwen_chatbot import QwenChatBot
from .resume_docx_generator import generate_resume_from_ai_response


# Create your views here.

def _generate_skills_data():
    """生成技能数据，格式为包含技能等级的字典"""
    skills_pool = [
        'Python', 'Java', 'JavaScript', 'React', 'Vue.js', 'Angular',
        'Node.js', 'Django', 'Flask', 'Spring Boot', 'MySQL', 'PostgreSQL',
        'MongoDB', 'Redis', 'Docker', 'Kubernetes', 'AWS', 'Azure',
        'Git', 'Jenkins', 'Linux', 'HTML', 'CSS', 'TensorFlow', 'PyTorch',
        'FASTAPI', 'CSS3', 'HTML5', 'Bootstrap', 'jQuery', 'TypeScript',
        'Next.js', 'Nuxt.js', 'Express', 'Koa', 'Electron', 'React Native',
        'Flutter', 'Swift', 'Kotlin', 'ReactVR', 'Unity3D', 'C#', 'C++',
        'Go', 'Rust', 'Scala', 'Elixir', 'Phoenix', 'Ruby', 'Rails',
        'PHP', 'Laravel', 'Symfony', 'Java Spring', 'MyBatis', 'Hibernate',
        'Oracle', 'SQL Server', 'SQLite', 'Cassandra', 'Neo4j', 'HBase',
        'Elasticsearch', 'Solr', 'Kibana', 'Logstash', 'Nginx', 'Apache',
        'Tomcat', 'Jboss', 'WebLogic', 'OpenShift', 'OpenStack', 'VMware',
        'Ansible', 'Puppet', 'Chef', 'Terraform', 'CloudFormation', 'Prometheus',
        'Grafana', 'Zabbix', 'Splunk', 'Datadog', 'New Relic', 'AppDynamics',
        'Selenium', 'JMeter', 'LoadRunner', 'Postman', 'SoapUI', 'Cucumber',
        'Jenkins X', 'GitLab CI', 'Travis CI', 'CircleCI', 'Bamboo', 'TeamCity',
        'Maven', 'Gradle', 'Ant', 'SonarQube', 'Checkmarx', 'Fortify',
        'OAuth', 'JWT', 'SAML', 'OpenID Connect', 'LDAP', 'Active Directory',
        'TCP/IP', 'HTTP/HTTPS', 'DNS', 'DHCP', 'BGP', 'OSPF', 'MPLS',
        'Firewall', 'IDS/IPS', 'VPN', 'SIEM', 'DDoS防护', '渗透测试',
        '区块链', '以太坊', 'Hyperledger', '智能合约', 'Solidity', 'Web3.js',
        '机器学习', '深度学习', '自然语言处理', '计算机视觉', '数据挖掘', '强化学习'
    ]

    skill_levels = ['精通', '熟练', '了解', '基础']

    # 从技能池中随机选择最多100个技能
    selected_skills = random.sample(
        skills_pool,
        min(10, len(skills_pool))
    )

    # 为每个技能分配一个等级
    skills_dict = {}
    for skill in selected_skills:
        skills_dict[skill] = random.choice(skill_levels)

    return skills_dict


class ResumeGeneratorAPIView(APIView):

    def _clean_ai_response(self, response_text):
        """
        清理AI返回的内容，移除markdown代码块标记
        """
        import re
        
        # 移除markdown代码块标记
        cleaned = re.sub(r'^```json\s*', '', response_text.strip())
        cleaned = re.sub(r'\s*```$', '', cleaned)
        
        # 移除可能的其他代码块标记
        cleaned = re.sub(r'^```\s*', '', cleaned)
        cleaned = re.sub(r'\s*```$', '', cleaned)
        
        return cleaned.strip()

    def post(self, request):
        """
               生成简历
       """
        user_base_info = {
            "jiben_info": {
                "name": "",
                "sex": "",
                "birthdate": "",
                "phone": "",
                "email": "",
                "description": "",
                "education": "",
                "current_status": ""

            },
            "desired": {
                "desired_position": "",
                "desired_money": "",
                "desired_city": ""
            },
            "work_experience": [

            ],
            "skills": {

            }
        }


        user_id = request.data.get('user_id')
        # 期望岗位
        desired_position = request.data.get('desired_position')
        # 期望城市
        desired_city = request.data.get('desired_city')
        # 期望薪资
        desired_money = request.data.get('desired_money')

        user_base_info["desired"]["desired_position"] = desired_position
        user_base_info["desired"]["desired_city"] = desired_city
        user_base_info["desired"]["desired_money"] = desired_money

        user = User.objects.get(id=user_id)
        user_base_info["jiben_info"]["name"] = user.username
        user_base_info["jiben_info"]["phone"] = user.phone
        user_base_info["jiben_info"]["email"] = user.email


        education_map = {
            1: '初中以下',
            2: '初中',
            3: '中专'
        }

        current_status_map = {
            1: '在职看机会',
            2: '离职'
        }

        sex_map = {
            1: '男',
            2: '女'
        }

        job_info = JobInfo.objects.filter(user=user).first()
        user_base_info["jiben_info"]["birthdate"] = job_info.birthdate
        user_base_info["jiben_info"]["description"] = job_info.description
        user_base_info["jiben_info"]["education"] = education_map.get(job_info.education)
        user_base_info["jiben_info"]["current_status"] = current_status_map.get(job_info.current_status)
        user_base_info["jiben_info"]["sex"] = sex_map.get(job_info.sex)

        work_experience = WorkExperience.objects.filter(job_info=job_info).all()

        industry_map = {
            1: "IT互联网",
            2: "金融",
            3: "医疗",
            4: "教育",
            5: "广告",
            6: "咨询",
            7: "建筑",
            8: " Transport",
            9: "能源",
            10: "政府",
            11: "其他"
        }

        work_experience_list = []
        for work_exp in work_experience:
            # 处理日期格式
            start_date = work_exp.start_date.strftime('%Y-%m-%d') if work_exp.start_date else ""
            end_date = work_exp.end_date.strftime('%Y-%m-%d') if work_exp.end_date else "至今"
            
            work_experience_info = {
                "company": work_exp.company,
                "description": work_exp.description,
                "end_date": end_date,
                "start_date": start_date,
                "position": work_exp.position,
                "salary_range": work_exp.salary_range,
                "industry": industry_map.get(work_exp.industry),
            }

            work_experience_list.append(work_experience_info)

        user_base_info["work_experience"] = work_experience_list

        skills=_generate_skills_data()

        user_base_info['skills'] = skills


        # 数据评分,自己完善,判断,10,15 算出来的分数/总分 >80%
        score = 0
        if user_base_info['jiben_info']['name']:
            score += 1
        if user_base_info['jiben_info']['phone']:
            score += 1

        work_experience_text = []
        for work_exp in user_base_info['work_experience']:
            work_experience_info = {
                "公司名": work_exp.get('company'),
                "开始时间": work_exp.get('start_date'),
                "结束时间": work_exp.get('end_date'),
                "职位": work_exp.get('position'),
                "工作描述": work_exp.get('description'),
                "所属行业": work_exp.get('industry'),
                "薪资范围": work_exp.get('salary_range')
            }

            work_experience_text.append(work_experience_info)


        prompt_text = f""" 
        ## 角色定位
            你是一个专业的人力资源专家,主要负责简历分析和写作
        ## 任务描述:
            请根据我提供的候选人的相关信息,
            根据候选人现有的专业技能和工作经历,增加一项项目经历,一共至少5个项目,内容包括:项目名称,项目描述,项目角色,项目时间,项目技术栈,个人指责
            整合所有的信息,生成一份优质的中文面试简历
            
        ## 格式输出要求
            简历内容以json格式的返回
        ## 以下是候选人的信息:
        ### 基本信息:
            姓名:{user_base_info['jiben_info']['name']}
            手机号:{user_base_info['jiben_info']['phone']}
            性别:{user_base_info['jiben_info']['sex']}
            出生日期:{user_base_info['jiben_info']['birthdate']}
            学历信息:{user_base_info['jiben_info']['education']}
            邮箱:{user_base_info['jiben_info']['email']}
            当前状态:{user_base_info['jiben_info']['current_status']}
            个人评价:{user_base_info['jiben_info']['description']}

        ### 求职意向:
            岗位:{user_base_info['desired']['desired_position']}
            期望薪资:{user_base_info['desired']['desired_money']}
            城市:{user_base_info['desired']['desired_city']}
    
        ### 工作经历:
            {work_experience_text}

        ### 专业技能:
            {user_base_info['skills']}
        """

        print("生成简历的提示词:", prompt_text)
        messages = [{
            "role": "user",
            "content": prompt_text
        }]

        def get_response(messages):
            client = OpenAI(
                # 若没有配置环境变量，请用阿里云百炼API Key将下行替换为：api_key="sk-xxx",
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
            )
            # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
            completion = client.chat.completions.create(model="qwen-plus", messages=messages)
            return completion

            # 将用户问题信息添加到messages列表中
            # messages.append({"role": "user", "content": question})
            # print(f"用户问题：{question}")
            # print("\n")

        print(f"messages:{messages}")
        assistant_output = get_response(messages).choices[0].message.content

        print("生成简历的答案:", assistant_output)
        
        # 清理AI返回的内容，移除markdown代码块标记
        cleaned_output = self._clean_ai_response(assistant_output)

        # 生成Word格式简历文档
        try:
            # 生成文件名
            username = user_base_info['jiben_info']['name'] or f"user_{user_id}"
            filename = f"{username}_简历.docx"
            
            # 生成Word文档
            file_path = generate_resume_from_ai_response(cleaned_output, filename)
            
            # 获取相对路径用于前端访问
            relative_path = os.path.relpath(file_path, settings.MEDIA_ROOT)
            download_url = f"{settings.MEDIA_URL}{relative_path}"
            
            print(f"简历文档生成成功: {file_path}")
            
            return Response({
                "code": 1,
                "message": "简历生成成功",
                "data": {
                    "resume_content": cleaned_output,
                    "docx_file_path": file_path,
                    "download_url": download_url,
                    "filename": filename
                }
            })
            
        except Exception as e:
            print(f"Word文档生成失败: {str(e)}")
            # 如果Word生成失败，仍然返回JSON数据
            return Response({
                "code": 1,
                "message": "简历内容生成成功，但Word文档生成失败",
                "data": {
                    "resume_content": cleaned_output,
                    "error": str(e)
                }
            })


class ResumeDownloadView(APIView):
    """简历文档下载视图"""
    
    def get(self, request, filename):
        """
        下载生成的简历文档
        """
        try:
            # 构建文件路径
            file_path = os.path.join(settings.MEDIA_ROOT, 'generated_resumes', filename)
            
            # 检查文件是否存在
            if not os.path.exists(file_path):
                return Response({
                    "code": 0,
                    "message": "文件不存在",
                    "data": None
                }, status=404)
            
            # 返回文件响应
            response = FileResponse(
                open(file_path, 'rb'),
                as_attachment=True,
                filename=filename,
                content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            )
            
            return response
            
        except Exception as e:
            return Response({
                "code": 0,
                "message": f"下载失败: {str(e)}",
                "data": None
            }, status=500)